﻿using System.IO;
using UnityEngine;

public class UnitObject : ObjectBase
{
    public nUnitData _unitData = null;

    public UnitObject(nUnitData data, int layer) : 
        base( data._unit_name, layer)
    {
        _unitData = data;

        _WorldPos = data._Pos;

        _Object.transform.position = data._Pos;
    }

    public nRhombusVBOData _VBOdata;

    public override void Load()
    {
        base.Load();

        //  对象
        _SR.sprite =  ZoneManager.Instance._ZoneMediaManager.GetResource2DObject<Sprite>(_unitData);

        //
        _bc2d.size = new Vector2(_SR.sprite.bounds.size.x, _SR.sprite.bounds.size.y);
        _bc2d.offset = new Vector2(_SR.sprite.bounds.size.x / 2, _SR.sprite.bounds.size.y / 2);
        
        //
        _dc.ReBorder(_unitData._Width, _unitData._Height);
        _dc.ReRhombus(_unitData._Width, _unitData._Width / ZoneCfg.RhombusFactor);

        //
        _VBOdata = new nRhombusVBOData(_unitData._Width, _unitData._Width / ZoneCfg.RhombusFactor);
        float n = _unitData._Width / ZoneCfg.RhombusMin;

        _rgc = _Object.AddComponent<RhombusGridComponent>();
        _rgc.FormatInscribed(Mathf.RoundToInt(n), _VBOdata);
    }

    public override bool Save()
    {
        if (_Object == null)
        {
            Debug.LogError("UnitObject.Save == null");

            //return false;
        }

        if (_GroudOrder == -1)
        {
            Debug.LogError("UnitObject.Save _GroudOrder == -1");

            //return false;
        }

        //_unitData._sortingOrder = _SR.sortingOrder;
        _unitData._Pos = _SR.transform.position;

        return true;
    }

    void ReadCfg(string spritecfgname)
    {
        if (!File.Exists(spritecfgname))
            return;

        BinaryReader reader = new BinaryReader(File.Open(spritecfgname, FileMode.Open));
        char isSel = reader.ReadChar();

        _isSelect = (isSel == '1') ? true : false;

        reader.Close();
    }


    public override void Unload()
    {
        if (_SR != null)
            _SR.sprite = null;

        base.Unload();
    }

    /// <summary>
    /// 获取标准菱形左顶点的世界坐标.
    /// </summary>
    /// <returns></returns>
    public Vector3 GetUnitRhombusLeft4World()
    {
        return _Object.transform.position + _VBOdata._left;
    }

    /// <summary>
    /// 设置当前在Groud下的坐标
    /// </summary>
    /// <param name="world_pos"></param>
    public void SetUnitRhombusLeft4World(Vector3 world_pos, int _groudorder)
    {
        _GroudOrder = _groudorder;

        _Object.transform.position = world_pos;

        _WorldPos = world_pos;
    }
}
